<template>
  <div class="teacher-bg">
    <div class="teacher-bg-mask"></div>
    <div class="teacher-score-container">
      <NoticeBoard :notices="noticeList" />
      <TeacherInfo />
      <ClassStats :scores="filteredScores" />
      <div class="header-bar">
        <h2>学生成绩管理系统</h2>
        <div>
          <el-button type="primary" @click="noticeDialogVisible = true" class="notice-btn">发布通知</el-button>
          <el-button type="danger" @click="logout" class="logout-btn">退出</el-button>
        </div>
      </div>
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入学生姓名或学号搜索"
          style="width: 300px; margin-right: 10px;"
          clearable
          @input="handleSearch"
        />
        <el-button type="primary" @click="fetchStudentScores">查询成绩</el-button>
      </div>
      
      <el-table :data="filteredScores" style="width: 100%; margin-top: 20px;">
        <el-table-column prop="studentId" label="学号" width="120" />
        <el-table-column prop="studentName" label="学生姓名" width="120" />
        <el-table-column prop="courseId" label="课程编号" width="120" />
        <el-table-column prop="courseName" label="课程名称" />
        <el-table-column prop="score" label="成绩" width="100">
          <template #default="scope">
            <span :class="getScoreClass(scope.row.score)">{{ scope.row.score }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="credit" label="学分" width="100" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" type="primary" @click="editScore(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="confirmDeleteScore(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog v-model="editDialogVisible" title="编辑成绩" width="350px">
        <el-form :model="editForm">
          <el-form-item label="学生姓名">
            <el-input v-model="editForm.studentName" disabled />
          </el-form-item>
          <el-form-item label="课程名称">
            <el-input v-model="editForm.courseName" disabled />
          </el-form-item>
          <el-form-item label="成绩">
            <el-input v-model.number="editForm.score" type="number" min="0" max="100" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditScore">保存</el-button>
        </template>
      </el-dialog>

      <el-dialog v-model="deleteDialogVisible" title="删除成绩" width="300px">
        <span>确定要删除 <b>{{ deleteTarget.studentName }}</b> 的 <b>{{ deleteTarget.courseName }}</b> 成绩吗？</span>
        <template #footer>
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="submitDeleteScore">删除</el-button>
        </template>
      </el-dialog>

      <el-dialog v-model="noticeDialogVisible" title="发布通知" width="420px">
        <el-input
          v-model="noticeContent"
          type="textarea"
          :rows="5"
          placeholder="请输入通知内容（最多200字）"
          maxlength="200"
          show-word-limit
          class="notice-input"
        />
        <template #footer>
          <el-button @click="noticeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitNotice">发布</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
  <BottomNav />
</template>

<script setup>
import BottomNav from '../components/BottomNav.vue'
import { ref, onMounted, computed } from 'vue'
import { useUserStore } from '../store/user'
import axios from 'axios'
import { useRouter } from 'vue-router'
import NoticeBoard from '../components/NoticeBoard.vue'
import TeacherInfo from '../components/TeacherInfo.vue'
import ClassStats from '../components/ClassStats.vue'
import request from '../utils/request'

const userStore = useUserStore()
const router = useRouter()
const scores = ref([])
const searchKeyword = ref('')

// 编辑弹窗相关
const editDialogVisible = ref(false)
const editForm = ref({})

// 删除弹窗相关
const deleteDialogVisible = ref(false)
const deleteTarget = ref({})

// 通知相关
const noticeList = ref(['请及时录入学生成绩，成绩录入截止时间为本月25日。'])
const noticeDialogVisible = ref(false)
const noticeContent = ref('')

// 过滤后的成绩数据
const filteredScores = computed(() => {
  if (!searchKeyword.value) {
    return scores.value
  }
  return scores.value.filter(item => 
    item.studentName.includes(searchKeyword.value) ||
    item.studentId.includes(searchKeyword.value)
  )
})

// 获取成绩样式类
const getScoreClass = (score) => {
  if (score >= 90) return 'score-excellent'
  if (score >= 80) return 'score-good'
  if (score >= 70) return 'score-average'
  if (score >= 60) return 'score-pass'
  return 'score-fail'
}

// 搜索处理
const handleSearch = () => {
  // 实时搜索，不需要额外处理，computed 会自动更新
}

// 获取学生成绩
const fetchStudentScores = async () => {
  try {
    const teacherId = userStore.teacherId || localStorage.getItem('teacherId')
    const res = await axios.get('/api/teacher/student-scores', { 
      params: { teacherId } 
    })
    
    if (res.data.code === 200) {
      scores.value = res.data.data
    } else {
      scores.value = []
      alert(res.data.msg || '查询失败')
    }
  } catch (error) {
    console.error('获取学生成绩失败:', error)
    scores.value = []
    alert('网络错误，请稍后重试')
  }
}

// 编辑成绩
const editScore = (row) => {
  editForm.value = { ...row }
  editDialogVisible.value = true
}

const submitEditScore = async () => {
  try {
    const res = await axios.put('/api/teacher/update-score', {
      studentId: editForm.value.studentId,
      courseId: editForm.value.courseId,
      score: editForm.value.score,
      teacherId: userStore.teacherId || localStorage.getItem('teacherId')
    })
    if (res.data.code === 200) {
      editDialogVisible.value = false
      fetchStudentScores()
      alert('成绩修改成功')
    } else {
      alert(res.data.msg || '成绩修改失败')
    }
  } catch (error) {
    alert('网络错误，修改失败')
  }
}

// 删除成绩
const confirmDeleteScore = (row) => {
  deleteTarget.value = { ...row }
  deleteDialogVisible.value = true
}

const submitDeleteScore = async () => {
  try {
    const res = await axios.delete('/api/teacher/delete-score', {
      studentId: deleteTarget.value.studentId,
      courseId: deleteTarget.value.courseId,
      teacherId: userStore.teacherId || localStorage.getItem('teacherId')
    })
    if (res.data.code === 200) {
      deleteDialogVisible.value = false
      fetchStudentScores()
      alert('成绩删除成功')
    } else {
      alert(res.data.msg || '成绩删除失败')
    }
  } catch (error) {
    alert('网络错误，删除失败')
  }
}

const submitNotice = async () => {
  if (!noticeContent.value.trim()) {
    return alert('通知内容不能为空')
  }
  try {
    const res = await request.put('/teacher/notice', {
      teacherId: userStore.teacherId || localStorage.getItem('teacherId'),
      content: noticeContent.value.trim()
    })
    if (res.data.code === 200) {
      noticeList.value.unshift(noticeContent.value.trim())
      noticeDialogVisible.value = false
      noticeContent.value = ''
      alert('通知发布成功')
    } else {
      alert(res.data.msg || '通知发布失败')
    }
  } catch (e) {
    alert('网络错误，通知发布失败')
  }
}

const logout = () => {
  userStore.clearUserInfo()
  localStorage.clear()
  router.push('/')
}

onMounted(() => {
  fetchStudentScores()
})
</script>

<style scoped>
.teacher-bg {
  min-height: 100vh;
  width: 100vw;
  position: relative;
  background: linear-gradient(120deg, #a1c4fd 0%, #c2e9fb 100%);
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-top: 40px;
  overflow-x: hidden;
}
.teacher-bg-mask {
  position: absolute;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(255,255,255,0.45);
  pointer-events: none;
  z-index: 0;
}
.teacher-score-container {
  position: relative;
  z-index: 1;
  background: rgba(255,255,255,0.98);
  border-radius: 22px;
  box-shadow: 0 8px 32px 0 rgba(80,120,200,0.10);
  padding: 38px 32px 32px 32px;
  min-width: 340px;
  max-width: 900px;
  width: 100%;
  margin-bottom: 40px;
  margin-top: 0;
  transition: box-shadow 0.2s;
}
.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.logout-btn {
  margin-left: 20px;
}
.notice-btn {
  margin-right: 10px;
}
.notice-input {
  margin-bottom: 8px;
}
@media (max-width: 600px) {
  .teacher-score-container {
    padding: 18px 4vw 18px 4vw;
    min-width: unset;
    max-width: 100vw;
    border-radius: 10px;
  }
}

.search-section {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.score-excellent {
  color: #67c23a;
  font-weight: bold;
}

.score-good {
  color: #409eff;
  font-weight: bold;
}

.score-average {
  color: #e6a23c;
  font-weight: bold;
}

.score-pass {
  color: #f56c6c;
  font-weight: bold;
}

.score-fail {
  color: #f56c6c;
  font-weight: bold;
  background-color: #fef0f0;
  padding: 2px 6px;
  border-radius: 3px;
}
</style> 